package com.bazinga.contact.view;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.*;


public class LoginAction extends ActionSupport implements SessionAware{
	private static final long serialVersionUID = -7219561392019888383L;
	private String username = null;
	private String password = null;
	private String userid = null;
	private String userType = null;
	

	private final String dbServer = "127.0.0.1";
	private Map<String, Object> session;
	
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
       
	@RequiredStringValidator(message="Please enter your email")
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@RequiredStringValidator(message="Please enter your password")
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public String execute() {
		String user = getUsername();
		String pass = getPassword();
		String firstName = null;
		
		String dbUrl = "jdbc:mysql://" + dbServer + ":3306/";
		String dbName = "bazinga";
		String driverName = "org.gjt.mm.mysql.Driver";
		String username = "root";
		String password = "";
		ResultSet rs = null;
		Connection conn = null;
		Statement stmt = null;
		
		String searchQuery = "select * from userdetails where email='" + user + "' and passwd='" + pass +"';";
		try
		{
			Class.forName(driverName).newInstance();
			conn = DriverManager.getConnection(dbUrl + dbName, username, password);
			stmt = conn.createStatement();
		}
		catch (Exception e) {
			System.out.println(e.toString());
		}
		try {
			rs = stmt.executeQuery(searchQuery);
		} 
		
		catch (SQLException e) {
			e.printStackTrace();
			return "error";
		}
		
		try {
			if(rs.first()) {
				firstName = rs.getString("fname");
				userid = rs.getString("userid");
				if(rs.getString("is_student").toString().equals("1"))
					userType = "student";
				else
					userType = "employer";
			}
			else
				return "login";
		}
		
		catch(SQLException ex) {
			ex.printStackTrace();
			return "error";
		}


  	  	session.put("logged-in","true");
  	  	session.put("username", user.toString());
  	  	session.put("firstname", firstName);
  	  	session.put("userid", userid);
  	  	session.put("usertype", userType);
  	  	
		return userType;
	}

}
